<template>
  <div>
    <el-card>
      <div style="margin-left:10px">
        <el-input style="float:left;width:200px;margin-left:10px" v-model="searchByName" class='searchByName'
                  placeholder="请输入药品关键字"/>
        <!-- <i class="el-icon-search"></i> -->
        <el-button type="primary" @click="searchByNameFun" style="margin-left: 20px;">查询</el-button>
        <el-button style="margin:10px 10px" type="success" @click="addShow=true">添加新药品</el-button>
      </div>
      <!-- 设置添加按钮 -->
      <!--      <el-button style="margin:10px 0px" type="success" size="mini" @click="addShow = true">添加新药品</el-button>-->
      <el-table border  :data="tableData" style="width: 100%">
        <el-table-column label="药品名称" width="240">
          <template slot-scope="scope">
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium">{{ scope.row.name }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图片" width="150" prop="createTime">
          <template slot-scope="scope">
            <img :src="scope.row.image" style="width: 100px; height: 80px"/>
          </template>
        </el-table-column>
        <!--        <el-table-column label="备注" width="240" prop="remark"></el-table-column>-->
        <el-table-column label="备注" width="150">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>备注: {{ scope.row.content }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">点击查看</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="种类" width="240" prop="category"></el-table-column>
        <el-table-column label="库存" width="240" prop="sum">

        </el-table-column>

<!--        <el-table-column label="审核状态" width="240" prop="address">-->
<!--          <template slot-scope="scope">-->
<!--            <el-tag type="primary"-->
<!--                    v-if="scope.row.checked===0"-->
<!--                    disable-transitions>-->
<!--              未审核-->
<!--            </el-tag>-->

<!--            <el-tag type="success"-->
<!--                    v-if="scope.row.checked===1"-->
<!--                    disable-transitions>-->
<!--              审核通过-->
<!--            </el-tag>-->

<!--            <el-tag type="danger"-->
<!--                    v-if="scope.row.checked===2"-->
<!--                    disable-transitions>-->
<!--              驳回-->
<!--            </el-tag>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="是否处方药" width="90">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.isPrescription === 0 ? false : true"
                       @change="stateChange(scope.row.isPrescription, scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="warning" @click="handleEdit(scope.$index, scope.row)">修改药品信息</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row>
        <el-col :span="12" :offset="12">
          <el-pagination layout="total,prev, pager, next,jumper,sizes " background small prev-text="上一页" next-text="下一页"
                         :total="total" :page-size="pageSize" :current-page="pageNow" :page-sizes="[5, 10, 50]"
                         style="margin:15px 0px"
                         @current-change="findPage" @size-change="findSize">
          </el-pagination>
        </el-col>
      </el-row>


    </el-card>
    <el-dialog title="添加药品" @close="closeDialog" :visible.sync="addShow"  :append-to-body="true" :modal-append-to-body="false">
      <el-form :model="form">
        <el-form-item label="药品名称" width="50%" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片" width="50%" :label-width="formLabelWidth">
          <!--          <el-input v-model="form.image" autocomplete="off"></el-input>-->
          <el-upload
              class="avatar-uploader"
              :action="action()"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-change="onChange"
              ref="upload"
          >
            <img
                v-if="form.image"
                :src="form.image"
                style="height: 200px;width: 200px"
                class="avatar"
            ></img>
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="价格" :label-width="formLabelWidth">
          <el-input v-model="form.price" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="库存" :label-width="formLabelWidth">
          <el-input v-model="form.stock" autocomplete="off"></el-input>
        </el-form-item>


        <el-form-item label="描述" :label-width="formLabelWidth">
          <el-input v-model="form.content" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="药品类型" :label-width="formLabelWidth">
          <el-select v-model="form.categoryId" placeholder="请选择药品类型">
            <el-option
                v-for="item in category"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

<!--        <el-form-item label="是否是处方药" :label-width="formLabelWidth" prop="isPrescription">-->
<!--          <template>-->
<!--            <el-radio v-model="form.isPrescription" label="0">普通药</el-radio>-->
<!--            <el-radio v-model="form.isPrescription" label="1">处方药</el-radio>-->
<!--          </template>-->
<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addShow = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  mounted() {
    this.findPage(this.pageNow, this.pageSize)
    this.getCategoryList()
  },
  data() {
    return {
      searchByName: '',
      pageNow: 1,
      pageSize: 5,
      total: 0,
      addShow: false,
      category: [],
      //添加药品型的表单
      form: {
        id: 0,
        name: '',
        price: 0,
        remark: '',
        image: '',
        categoryId: '',
        isPrescription: '0',
        stock: 0,
      },
      formLabelWidth: '120px',
      tableData: []
    }
  },
  methods: {
    getCategoryList() {
      this.$http.get("/category/select/list").then(res => {
        // this.tableData = res.data.data.records;
        // this.total = res.data.data.total
        this.category = res.data.data
        // console.log(res.data.data)
      });
    },

    closeDialog() {
      console.info(111)
      this.form = {
        id: 0,
        name: '',
        price: 0,
        remark: '',
        image: '',
        categoryId: 0,
        isPrescription: '0',
        stock: 0
      }
    },
    addSight(status) {
      this.addShow = true
    },

    action() {
      return "http://localhost:8081/common/upload"
    },
    handleAvatarSuccess(response, file, fileList) {
      // 拼接down接口预览
      // this.imageUrl = `/common/download?name=${response.data}`;
      // console.info("sakura");
      // console.info(response.data)
      this.form.image = "http://localhost:8081/common/download?name=" + response.data
      // console.info(this.form.image)
    },

    onChange(file) {
      if (file) {
        const suffix = file.name.split('.')[1]
        const size = file.size / 1024 / 1024 < 2
        if (['png', 'jpeg', 'jpg'].indexOf(suffix) < 0) {
          this.$message.error('上传图片只支持 png、jpeg、jpg 格式！')
          this.$refs.upload.clearFiles()
          return false
        }
        if (!size) {
          this.$message.error('上传文件大小不能超过 2MB!')
          return false
        }
        return file
      }
    },

    //管理员状态改变
    async stateChange(state, row) {
      console.info(state)
      const user = JSON.parse(window.sessionStorage.getItem("user"))
      const {data: res} = await this.$http.put(`/medicine/changeState/${row.id}/${state}`)
      if (res.status) {
        this.$message.success(res.data)
        this.searchByNameFun()
      } else {
        this.$message.error(res.msg)
      }
      this.findPage(this.pageNow)
    },

    // 根据物资的关键字查询
    searchByNameFun() {
      // console.log(this.searchByName)
      this.pageNow = 1

      if (this.value != '') {
        // 页面变动之后需要查询相同种类的变动页码的数据
        this.$http.get("/medicine/list/" + this.pageNow + "/" + this.pageSize + "?searchKey=" + this.searchByName).then(res => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total
          // console.log(this.tableData)
        });
        return
      }

    },
    //添加类型表单
    submitForm() {
      this.addShow = false
      console.log(this.form)
      this.$http.post("/medicine/addOrUpdate", this.form).then(res => {
        console.log(res.data)
        if (res.data.status) {
          this.$message({
            message: res.data.data,
            type: 'success'
          });
          this.form = {
            id: 0,
            name: '',
            price: 0,
            remark: '',
            image: '',
            categoryId: 0,
            isPrescription: '0',
            stock: 0
          }
          this.searchByNameFun()
        } else {
          this.form = {
            id: 0,
            name: '',
            price: 0,
            remark: '',
            image: '',
            categoryId: 0,
            isPrescription: '0',
            stock: 0
          }
          this.$message.error(res.data.msg);
        }
      })
      this.form = {}
      this.findPage(this.pageNow)
    },
    findSize(size) {
      // console.log(size)
      this.pageSize = size
      this.findPage(this.pageNow, this.pageSize)
    },
    findPage(page) {
      // console.log(page)
      this.pageNow = page
      if (this.value != '') {
        // 页面变动之后需要查询相同种类的变动页码的数据
        this.$http.get("/medicine/list/" + this.pageNow + "/" + this.pageSize + "?searchKey=" + this.searchByName).then(res => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total
          // console.log(this.tableData)
        });
        return
      }
      // this.findAll(page, this.size)
    },
    handleEdit(index, row) {
      // console.log(index, row);
      this.addShow = true
      // this.form = row
      this.pageNow = 1
      this.$http.get("/medicine/"+row.id,this.form).then(res=>{
        console.log(res.data.data)
        this.form = res.data.data
      })

      this.form = {}
      this.findPage(this.pageNow)
      this.form = {}
    },
    handleDelete(index, row) {
      // console.log(index, row);
      this.$http.delete("/medicine/delete/" + row.id).then(res => {
        // console.log(res.data)
        if (res.data.status) {
          this.$message({
            message: res.data.data,
            type: 'success'
          });
          this.pageNow = 1
          this.findPage(this.pageNow)
        } else {
          this.$message.error(res.data.msg);
        }
      })
    }
  },
  watch: {
    searchByName(newName, oldName) {
      if (newName === '') {
        // console.log("为空了")
        this.findPage(1)
      }
    }
  }

}
</script>

<style></style>
